<?php

namespace App\Http\Controllers\platform;

use App\Http\Controllers\Controller;
use App\Models\CompanyStudyTime;
use App\Models\Personal;
use App\Models\StudyUserTime;
use Illuminate\Http\Request;

class RankController extends Controller
{
    public function studyTime(Request $Request)
    {
        $limit = $Request->limit ?: 10;
        $page = $Request->page ?: 1;
        $page = $page * $limit - $limit;
        $start_time = $Request->start_time;
        $end_time = $Request->end_time;
        $data_ = StudyUserTime::with('user')->selectRaw('uid, SUM(study_length) as duration')
        ->where('eid',$Request->eid)->groupBy('uid')->orderBy('duration','desc')
        ->when($start_time, function ($query, $start_time) {
            return $query->where(function($query) use ($start_time) {
                $query->where('create_time','>', $start_time);
            });
        })
        ->when($end_time, function ($query, $end_time) {
            return $query->where(function($query) use ($end_time) {
                $query->where('create_time','<', $end_time);
            });
        })->get();
        $data = [];
        foreach ($data_ as $k => $v) {
            if($v->user){
                $data[] = $v;
            }
        }


        $task_ = CompanyStudyTime::with('user')->selectRaw('uid, SUM(duration) as duration')
        ->where('eid',$Request->eid)->groupBy('uid')->orderBy('duration','desc')
        ->when($start_time, function ($query, $start_time) {
            return $query->where(function($query) use ($start_time) {
                $query->where('create_time','>', $start_time);
            });
        })
        ->when($end_time, function ($query, $end_time) {
            return $query->where(function($query) use ($end_time) {
                $query->where('create_time','<', $end_time);
            });
        })->get();
        $task = [];
        foreach ($task_ as $k => $v) {
            if($v->user){
                $task[] = $v;
            }
        }

        $user_ = Personal::with('department')->select('id','name','head_img','department_id')->where('es_id',$Request->eid)->get();
        $user = [];
        foreach ($user_ as $k => $v) {
            $is_data = $data_->where('uid',$v->id)->first();
            $is_task = $task_->where('uid',$v->id)->first();
            if($is_data){
                $user_[$k]->duration = $is_data->duration;
            }
            if($is_task){
                $user_[$k]->duration += $is_task->duration;
            }
            if($user_[$k]->duration > 0){
                $user[] = $user_[$k];
            }
        }
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$data,'task'=>$task,'user'=>$user]);
    }

}
